C++ stack swap()用法及代码示例 | 您所在的位置:网站首页 › c++ 的swap › C++ stack swap()用法及代码示例 |
堆栈是一种具有LIFO(后进先出)类型的容器适配器,其中在一端添加了一个新元素,而(顶部)仅从该端删除了一个元素。 stack::swap()此函数用于将一个堆栈的内容与另一个相同类型的堆栈交换,但是大小可能会有所不同。 用法: stackname1.swap(stackname2)参数:必须与之交换内容的堆栈的名称。 结果:2个堆栈中的所有元素都被交换。 例子: contents of the stack from top to bottom are Input :mystack1 = {4, 3, 2, 1} mystack2 = {9, 7 ,5, 3} mystack1.swap(mystack2); Output:mystack1 = 9, 7, 5, 3 mystack2 = 4, 3, 2, 1 Input :mystack1 = {7, 5, 3, 1} mystack2 = {8, 6, 4, 2} mystack1.swap(mystack2); Output:mystack1 = 8, 6, 4, 2 mystack2 = 7, 5, 3, 1注意:在堆栈容器中,这些元素以相反的顺序打印,因为先打印顶部,然后再移动到其他元素。 // CPP program to illustrate // Implementation of swap() function #include #include using namespace std; int main() { // stack container declaration stack mystack1; stack mystack2; // pushing elements into first stack mystack1.push(1); mystack1.push(2); mystack1.push(3); mystack1.push(4); // pushing elements into 2nd stack mystack2.push(3); mystack2.push(5); mystack2.push(7); mystack2.push(9); // using swap() function to swap elements of stacks mystack1.swap(mystack2); // printing the first stack cout |
CopyRight 2018-2019 实验室设备网 版权所有 |